package com.wdd.recoveryvehicle.loginUser.controller;

import com.wdd.common.Result.Result;
import com.wdd.common.Result.ResultUtil;
import com.wdd.recoveryvehicle.loginUser.bean.LoginUserVB;
import com.wdd.recoveryvehicle.loginUser.service.LoginUserService;
import com.wdd.recoveryvehicle.loginUser.service.TokenService;
import org.hibernate.validator.constraints.NotBlank;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Validated
@RequestMapping("/loginUser")
@RestController
public class LoginUserController {
    private Logger logger = LoggerFactory.getLogger(LoginUserController.class);

    @Autowired
    private LoginUserService loginUserService;
    @Autowired
    private TokenService tokenService;

    /**
     * 用户登录
     *
     * @param user_nickname
     * @param user_password
     * @return
     */
    @PostMapping(value = "/userSignIn")
    public Result userSignIn(@NotBlank(message = "用户名为空") String user_nickname,
                             @NotBlank(message = "密码为空") String user_password) {

        logger.info("userSignIn 的参数 user_nickname: " + user_nickname + " ; user_password: " + user_password);

        LoginUserVB loginUserVB = loginUserService.selectLoginUserVBByUserNickname(user_nickname);
        if (loginUserVB == null || !loginUserVB.getUser_password().equals(user_password)) {
            System.out.println("账号密码错误 =========");
            return ResultUtil.error(400, "账号密码错误");
        } else {
            Map<String, Object> mapToken = tokenService.createToken(loginUserVB.getUser_id());
            mapToken.put("loginUser", loginUserVB);
            return ResultUtil.success(mapToken);
        }
    }

    /**
     * 用户登出
     *
     * @param token
     * @return
     */
    @PostMapping(value = "/userSignOut")
    public Result userSignOut(@NotBlank(message = "token为空") String token) {
        logger.info("userSignOut 的参数 token: " + token);
        tokenService.logout(token);
        return ResultUtil.success();
    }


}
